/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.hiddenequity.adgroup_criterion_service.AdGroupCriterionResponseParser;
import com.hiddenequity.adgroup_criterion_service.AdGroupCriterionService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.Converter;
import com.hiddenequity.utils.DataValidator;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;

public class Act_KeywordOperation extends Act_Super{
	
	private String keywordId;
	private String adGroupId;
	private String campaignName;
	private String adGroupName;
	private String campaignBidingStrategy;
	private String campaignBudget;
	private boolean criterionUse;
	
	private EditText edit_Keyword;
	private Spinner spin_keywordMatchType;
	private EditText edit_keywordMaxCpc;
	private Spinner spin_keywordUrlSchema;
	private EditText edit_keywordUrl;
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.super_operation_layout);
		
		((ViewStub) findViewById(R.id.stub_keyword_operation)).inflate();
		
        //Get intent data
        Intent intent = getIntent();
        keywordId = intent.getStringExtra("keywordId");
        adGroupId = intent.getStringExtra("adGroupId");
        campaignName =  intent.getStringExtra("campaignName");
        adGroupName =  intent.getStringExtra("adGroupName");
        campaignBidingStrategy = intent.getStringExtra("campaignBidingStrategy");
        campaignBudget = intent.getStringExtra("campaignBudget");
        criterionUse = intent.getBooleanExtra("criterionUse", true);
        
        //Set activity title
        title.setText(R.string.title_keyword_add);
        sub_title.setText(campaignName + " / " + adGroupName);
		filter.setVisibility(View.GONE);
        
		//Initialize form components
    	edit_Keyword = (EditText) findViewById(R.id.edit_Keyword);
    	spin_keywordMatchType = (Spinner) findViewById(R.id.spin_keywordMatchType);
    	edit_keywordMaxCpc = (EditText) findViewById(R.id.edit_keywordMaxCpc);
    	spin_keywordUrlSchema = (Spinner) findViewById(R.id.spin_keywordUrlSchema);
    	edit_keywordUrl = (EditText) findViewById(R.id.edit_keywordUrl);     

    	//SetUp form according to campaign bidding strategy
    	if(!campaignBidingStrategy.equals("ManualCPC")){
    		edit_keywordMaxCpc.setEnabled(false);
    	}
    	
    	//populate matchType spinner
		inflateSpinner(spin_keywordMatchType, R.array.arr_keywordtMatchTypes, 0);
		
        //populate url schema spinner
		inflateSpinner(spin_keywordUrlSchema, R.array.arr_urlSchemas, 0);
		
		if(!criterionUse){
			TextView lbl_Keyword_maxCpc = (TextView) findViewById(R.id.lbl_Keyword_maxCpc);
			
			edit_keywordMaxCpc.setVisibility(View.GONE);
			lbl_Keyword_maxCpc.setVisibility(View.GONE);
			
			LinearLayout tl_keyword_url = (LinearLayout) findViewById(R.id.ll_keyword_url);
			tl_keyword_url.setVisibility(View.GONE);
		}
		
		
		if(keywordId != null){
			title.setText(getString(R.string.title_keyword_set));
			runOperationAsync(OPERATION_GET_DATA, getString(R.string.progress_loading), false);
		}
    }//onCreate

    
    
    /*
     * Save button handler
     */
    public void onClick_saveData(View v){
    	if(isDataValid()){
        	runOperationAsync(OPERATION_SET_DATA, getString(R.string.progress_saving), false);
    	} else {
    		showOperationError(R.string.msg_title_invalid_data, formErrorString);
    	}	
    }//onClick_saveData
    

    
    /*
     * Save keyword
     */
    private boolean isChangesMade = true;
    
    private void keywordAddOperation(){
    	
    	if(initText.equals(keyword) && initMatchType.equals(matchType) && initMaxCpc.equals(maxCpc) &&
    			initDestinationUrl.equals(destignationUrl)){
    		isChangesMade = false;
    		return;
    	}
    	
    	String resp = Communication.postSOAP(
				AdGroupCriterionService.URL_ADGROUP_CRITERION_SERVICE, 
				AdGroupCriterionService.addKeywordOperation(keywordId, adGroupId, keyword,
						matchType, maxCpc, destignationUrl, criterionUse)
    		);

    	AdGroupCriterionResponseParser campaignParser = new AdGroupCriterionResponseParser(resp);
    	responseErrorString = campaignParser.checkForErrors();
    }//addKeyword
    
    
    
    /*
     * Remove keyword
     */

    private void keywordRemoveOperation(){
    	
    	if(keywordId == null || !isChangesMade)
    		return;
      	
    	if(initText.equals(keyword)){
    		isChangesMade = false;
    		return;
    	}
    	    	
    	String resp = Communication.postSOAP(
				AdGroupCriterionService.URL_ADGROUP_CRITERION_SERVICE, 
				AdGroupCriterionService.keywordRemoveOperation(adGroupId, keywordId, initText, initMatchType)
    		);

    	AdGroupCriterionResponseParser campaignParser = new AdGroupCriterionResponseParser(resp);
    	responseErrorString = campaignParser.checkForErrors();    		
    }//keywordRemoveOperation
    
    
    
    /*
     * Validate data
     */
    private String keyword;
    private String matchType;
    private String maxCpc;
    private String destignationUrl;
    
    private boolean isDataValid(){
    	boolean result = true;
        keyword = edit_Keyword.getText().toString();
        matchType = spin_keywordMatchType.getItemAtPosition(
        		spin_keywordMatchType.getSelectedItemPosition()).toString();
        maxCpc = edit_keywordMaxCpc.getText().toString();
        
        String urlSchema = spin_keywordUrlSchema.getItemAtPosition(
        		spin_keywordUrlSchema.getSelectedItemPosition()).toString();
        
        destignationUrl = edit_keywordUrl.getText().toString();
        
        if(!destignationUrl.equals(""))
        	destignationUrl = urlSchema + destignationUrl;
    	
    	if(!DataValidator.isKeyword(keyword)){
    		formErrorString = getString(R.string.msg_invalid_keyword);
    		edit_Keyword.requestFocus();
    		result = false;
    	} else if(!DataValidator.isAmount(maxCpc, true)){
    		formErrorString = getString(R.string.msg_invalid_keyword_maxcpc);
    		edit_keywordMaxCpc.requestFocus();
    		result = false;
    	} else if(!DataValidator.isUrl(destignationUrl, true, true)){
    		formErrorString = getString(R.string.msg_invalid_target_url);
    		edit_keywordUrl.requestFocus();
    		result = false;
    	} else if(!DataValidator.isBidNotExceedBudget(maxCpc, campaignBudget)){
    		formErrorString = getString(R.string.msg_api_bid_too_high);
    		edit_keywordMaxCpc.requestFocus();
    		result = false;
    	}

        return result;
    }//isDataValid
    
    
    
    /*
     * Asinc task
     */
	private void runOperationAsync(final int operation, String message, boolean overlap) {

		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_KeywordOperation.this, getApplication());
				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_GET_DATA:
							Act_KeywordOperation.this.getKeyword();
							break;

						case OPERATION_SET_DATA:
							Act_KeywordOperation.this.keywordAddOperation();
							break;

						case OPERATION_REMOVE_DATA:
							Act_KeywordOperation.this.keywordRemoveOperation();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				// Perform postoperation
				Act_KeywordOperation.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {
							case OPERATION_GET_DATA:
								setUpForm();
								break;

							case OPERATION_SET_DATA:
								if (responseErrorString == null)
									runOperationAsync(
											OPERATION_REMOVE_DATA,
											getString(R.string.progress_removing),
											true);
								break;

							case OPERATION_REMOVE_DATA:
								if (responseErrorString == null)
									if (isChangesMade) {
										finishActivityWithResult(RESPONSE_REFRESH_REQUIRED);
									} else {
										finishActivityWithResult(RESPONSE_NO_REFRESH_REQUIRED);
									}
								break;
							}
						} else {
							Intent intent = new Intent(
									Act_KeywordOperation.this
											.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();		
			
	}//runOperationAsync
    
	
	
	/*
	 * Get keyword data
	 */
	private Map<String, String> keywordData = new HashMap<String, String>();
	
	private void getKeyword(){
		keywordData.clear();
		String resp = Communication.postSOAP(
				AdGroupCriterionService.URL_ADGROUP_CRITERION_SERVICE, 
				AdGroupCriterionService.getKeywordById(adGroupId, keywordId)
    		);

    	AdGroupCriterionResponseParser campaignParser = new AdGroupCriterionResponseParser(resp);
    	responseErrorString = campaignParser.checkForErrors();
    	keywordData.putAll(campaignParser.getKeywordById());
	}//getKeyword
    
	
	
	/*
	 * Set Up Form
	 */
	private String initText = "";
	private String initMatchType = "";
	private String initMaxCpc = "";
	private String initDestinationUrl = "";
	
	private void setUpForm(){
		//Set init keyword data used in replacement operation
		initText = keywordData.get("text");
		initMatchType = keywordData.get("matchType");
		
		//Set keyword text
		edit_Keyword.setText(keywordData.get("text"));
		
		//Set match type spinner position
		String[] matchTypeArray =  getResources().getStringArray(R.array.arr_keywordtMatchTypes);
		ArrayList<String> matchTypeList = new ArrayList<String>(Arrays.asList(matchTypeArray));	
		int position = matchTypeList.indexOf(keywordData.get("matchType"));
		spin_keywordMatchType.setSelection(position);

		//Set maxCpc
		if(keywordData.get("bidSource") != null && keywordData.get("bidSource").equals("CRITERION")){
			initMaxCpc = Converter.microamountToStr(keywordData.get("maxCpc"));
			edit_keywordMaxCpc.setText(initMaxCpc);   
		}
		
		if(!campaignBidingStrategy.equals("ManualCPC")){
			edit_keywordMaxCpc.setText(
					getString(R.string.adgroup_bid_auto) + ": " + 
					Converter.microamountToStr(keywordData.get("maxCpc")));   
		}
		
		//Set destination URL
		initDestinationUrl = keywordData.get("destinationUrl");
		if(initDestinationUrl == null){
			initDestinationUrl = "";
		} else {
			if(initDestinationUrl.contains("http://")){
				edit_keywordUrl.setText(initDestinationUrl.replace("http://", ""));
				spin_keywordUrlSchema.setSelection(0);
			} else {
				edit_keywordUrl.setText(initDestinationUrl.replace("https://", ""));
				spin_keywordUrlSchema.setSelection(1);
			}
		}
		
	}//setUpForm
}
